package com.example.volunteer.service.impl;

import com.example.volunteer.exception.CustomException;
import com.example.volunteer.mapper.ActivityMapper;
import com.example.volunteer.model.Activity;
import com.example.volunteer.service.ActivityService;
import com.example.volunteer.util.PageResult;
import com.zaxxer.hikari.pool.HikariProxyCallableStatement;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class ActivityServiceImpl implements ActivityService {

    @Autowired
    private ActivityMapper activityMapper;

    @Override
    public void createActivity(Activity activity) {
        if (activity.getStartTime().before(new Date())) {
            throw new CustomException("开始时间不能是过去时间");
        }
        if (activity.getEndTime().before(activity.getStartTime())) {
            throw new CustomException("结束时间不能早于开始时间");
        }
        activity.setStatus("报名中"); // 设置默认状态
        activityMapper.insert(activity);
    }

    @Override
    public void updateActivity(Activity activity) {
        if (activity.getActivityId() == null) {
            throw new CustomException("活动ID不能为空");
        }

        Activity existing = activityMapper.findById(activity.getActivityId());
        if (existing == null) {
            throw new CustomException("活动不存在");
        }

        // Validate timestamps
        if (activity.getStartTime() != null && activity.getStartTime().before(new Date())) {
            throw new CustomException("开始时间不能是过去时间");
        }
        if (activity.getEndTime() != null && activity.getStartTime() != null
                && activity.getEndTime().before(activity.getStartTime())) {
            throw new CustomException("结束时间不能早于开始时间");
        }

        // Update fields
        BeanUtils.copyProperties(activity, existing, "activityId", "status", "adminId", "createdTime");
        activityMapper.update(existing);
    }

    @Override
    public void updateActivityStatus(Integer activityId, String status) {
        if (!"报名中".equals(status) && !"进行中".equals(status) && !"已结束".equals(status)) {
            throw new CustomException("状态值不合法");
        }
        activityMapper.updateStatus(activityId, status);
    }

    @Override
    public Activity findById(Integer activityId) {
        return activityMapper.findById(activityId);
    }

    @Override
    public void delete(Integer activityId) {
        activityMapper.delete(activityId);
    }

    @Override
    public PageResult<Activity> findActivitiesWithPage(int pageNum, int pageSize) {
        int offset = (pageNum - 1) * pageSize;
        List<Activity> activities = activityMapper.findActivitiesWithPage(offset, pageSize);
        int total = activityMapper.countActivities();

        PageResult<Activity> result = new PageResult<>();
        result.setData(activities);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setPages((int) Math.ceil((double) total / pageSize));

        return result;
    }
    @Override
    public PageResult<Activity> findByTitleWithPage(String title, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByTitleWithPage(title, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByTitle(title),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByStartTimeWithPage(Date startTime, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByStartTimeWithPage(startTime, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByStartTime(startTime),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByEndTimeWithPage(Date endTime, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByEndTimeWithPage(endTime, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByEndTime(endTime),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByAddressWithPage(String address, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByAddressWithPage(address, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByAddress(address),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByParticipantLimitWithPage(Integer participantLimit, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByParticipantLimitWithPage(participantLimit, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByParticipantLimit(participantLimit),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByCreatedTimeWithPage(Date createdTime, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByCreatedTimeWithPage(createdTime, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByCreatedTime(createdTime),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByAdminIdWithPage(String adminId, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByAdminIdWithPage(adminId, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByAdminId(adminId),
                pageNum,
                pageSize
        );
    }

    @Override
    public PageResult<Activity> findByStatusWithPage(String status, int pageNum, int pageSize) {
        return createPageResult(
                activityMapper.findByStatusWithPage(status, calculateOffset(pageNum, pageSize), pageSize),
                activityMapper.countByStatus(status),
                pageNum,
                pageSize
        );
    }


    // 辅助方法
    private int calculateOffset(int pageNum, int pageSize) {
        return (pageNum - 1) * pageSize;
    }

    private PageResult<Activity> createPageResult(List<Activity> data, int total, int pageNum, int pageSize) {
        PageResult<Activity> result = new PageResult<>();
        result.setData(data);
        result.setTotal(total);
        result.setPageNum(pageNum);
        result.setPageSize(pageSize);
        result.setPages((int) Math.ceil((double) total / pageSize));
        return result;
    }
}